<template>
  <view class="quiz-page">
    <z-nav-bar backState='1000' type='transparent' :titleCenter='false' :title='topSj.bankName'></z-nav-bar>
    <!-- 公共组件-每个页面必须引入 -->
    <public-module></public-module>
    
    <!-- 头部标题区域 -->
    <view class="header-section" style="display: flex;justify-content: center;align-items: center;">
      <view class="subtitle-text" v-if="currentQuestion.isPublic == 1">基础信息题（不计分）</view>
      <view class="subtitle-text" v-if="currentQuestion.isPublic == 0">考试题（计分）</view>
      <view class="subtitle-text" v-if="currentQuestion.isPublic == 2">调查问卷题（不计分）</view>
      <view class="progress-text">{{currentQuestionIndex+1}}/{{questionsVOS.length}}</view>
    </view>

	<view style="width: 100%;text-align: center;position: relative;top: 10px;" v-if="timeshow">
		<text style="font-size: 25px;color: red;">倒计时：{{ displayTime }}</text>
	</view>
	
    <!-- 问题外层白色圆角框 -->
    <transition name="fade" mode="out-in">
      <view class="question-wrapper" :key="currentQuestionIndex">
        <!-- 问题区域 -->
        <view class="question-container">
			<view class="question-flex" v-if="ShowPub3res.length >0">
				<view class="question" style="font-size: 18px;"><span style="color: #ffd966;padding: 5px;">{{ShowPub3res[0].isMultipleChoice == 0 ? '(单选)' : '(多选)'}}</span><span style="margin-left: 10px;">{{ ShowPub3res[0].content }} </span></view>
				<image v-if="ShowPub3res[0].examUrl" :src="'http://124.222.44.60:9090/jeecg-boot/sys/common/static/' + ShowPub3res[0].examUrl" mode="aspectFit" class="question-image" @click="previewImage('http://124.222.44.60:9090/jeecg-boot/sys/common/static/' + ShowPub3res[0].examUrl)"></image>
			</view>
			<view class="question-flex" v-else>
				<view class="question" style="font-size: 18px;"><span style="background-color: #ffd966;padding: 5px;">{{currentQuestion.isMultipleChoice == 0 ? '(单选)' : '(多选)'}}</span><span style="margin-left: 10px;">{{ currentQuestion.content }}</span></view>
				<image v-if="currentQuestion.examUrl" :src="'http://124.222.44.60:9090/jeecg-boot/sys/common/static/' + currentQuestion.examUrl" mode="aspectFit" class="question-image" @click="previewImage('http://124.222.44.60:9090/jeecg-boot/sys/common/static/' + currentQuestion.examUrl)"></image>
			</view>
        </view>

        <!-- 选项区域 -->
        <view v-for="(option, index) in  ShowPub3res.length >0 ? ShowPub3res[0].optionsVOS :currentQuestion.optionsVOS" :key="index" class="option" @click="selectOption(index)">
          <view :class="isSelected(index) ? 'selected option-text' : 'option-text'">{{ String.fromCharCode(65 + index) }}. {{ option.content }}</view>
        </view>
        <!-- 填空题输入框（无选项时显示） -->
        <view v-if="ShowPub3res.length === 0 && (!currentQuestion.optionsVOS || currentQuestion.optionsVOS.length === 0)" class="option">
          <textarea v-model="currentQuestion.fillAnswer" placeholder="请输入内容" auto-height style="width:100%;min-height:100rpx;padding:12px;background:#f5f5f5;border-radius:10px;font-size:16px;"></textarea>
        </view>
      </view>
    </transition>
	
	<!-- 遮罩层 -->  
	    <div v-if="showPopup" class="mask"></div>  
		<view class="tjda"  v-if="showPopup">
			<view style="text-align: center;"><img src='@/static/dati/tishi.png' style="height: 80px;width: 70px;"></view>
			<view style="text-align: center;font-size: 16px;font-weight: 600;letter-spacing: 1px;">请再次确认提交答卷!</view>
			<view class="navigation">
			  <button @click="tijiaodajuan" style='margin-top: 20px;' class="nav-button1">提交答卷</button>
			  <button style='margin-top: 10px;'  class="nav-button1" @click="showPopup = false">取消提交</button>
			</view>
			<view style="margin: 10px;color: red;">{{unansweredQuestionsStr ? unansweredQuestionsStr : ''}}</view>
		</view>
		<div v-if="showPopup1" class="mask"></div>
		<view class="tjda1"  v-if="showPopup1">
			<view style="text-align: center;"><img src='@/static/dati/tishi.png' style="height: 80px;width: 70px;"></view>
			<view style="text-align: center;font-size: 16px;font-weight: 600;letter-spacing: 1px;">考试已经结束!</view>
			<view class="navigation">
			  <button @click="qued" class="nav-button1">确定</button>
			</view>
		</view>
		
		<!-- 图片预览遮罩层 - 最高层级 -->
		<view v-if="showImagePreview" class="image-preview-mask" @click="closeImagePreview">
			<view class="image-preview-container" @click.stop>
				<image 
					:src="currentImageUrl" 
					class="preview-image"
					:style="{ transform: `scale(${imageScale}) translate(${imagePosition.x}px, ${imagePosition.y}px)` }"
					mode="aspectFit"
					@touchstart="onImageTouchStart"
					@touchmove="onImageTouchMove"
					@touchend="onImageTouchEnd"
					@dblclick="onImageDoubleClick"
				></image>
			</view>
			<view class="image-preview-close" @click="closeImagePreview">✕</view>
		</view>
    
    <!-- 底部按钮区域 -->
    <view class="bottom-navigation">
      <button @click="prevQuestion" class="nav-button" :disabled="transitioning">上一题</button>
	  <button @click="$noMultipleClicks(submits(),1000)" class="nav-button" :disabled="transitioning" v-if="currentQuestionIndex == questionsVOS.length-1">提交答卷</button>
      <button @click="nextQuestion" class="nav-button" :disabled="transitioning" v-else>下一题</button>
    </view>
	
  </view>
</template>





<script>
import store from '@/store';
import $http from '@/config/requestConfig'
export default {
  data() {
    return {
		ksid:'',
		subarr2:[],
		ShowPub3res:[],
		indexvo:null,
		isPublic3Array:[],
		timeshow:false,
		  countdown: null,
		  minutes:"",
		       totalMinutes: 2, // 从后端获取的分钟字段
		       timeLeft: 0, // 剩余时间（秒）
			   countdownStarted: false, // 用于判断倒计时是否已启动
		unansweredQuestions:[],
		unansweredQuestionsStr:'',
		showPopup:false,
		showPopup1:false,
		// 图片预览相关
		showImagePreview: false,
		currentImageUrl: '',
		imageScale: 1,
		imagePosition: { x: 0, y: 0 },
		touchStart: { x: 0, y: 0 },
		lastTouchDistance: 0,
		touchStartScale: 1,
      currentQuestionIndex: 0,
	  transitioning: false, // 控制动画时不允许多次点击
	  arr2QuestionsVOS:[],
      questionsVOS: [
        {
          question: "传染病流行是指?",
          optionsVOS: [
			      {
			          "id": 1,
			          "questionId": 1,
			          "content": "饿着",
			          "number": "A",
					  selected: false 
			      },
			      {
			          "id": 2,
			          "questionId": 1,
			          "content": "等着",
			          "number": "B",
					  selected: false 
			      }
          ],
          isMultipleChoice: false // 单选还是多选
        }, {
          question: "1111?",
          optionsVOS: [
            {
                "id": 1,
                "questionId": 1,
                "content": "饿着",
                "number": "A",
            					  selected: false 
            },
            {
                "id": 2,
                "questionId": 1,
                "content": "等着",
                "number": "B",
            	selected: false 
            }
          ],
          isMultipleChoice: true // 单选还是多选
		  
        },
        // 其他问题...
      ],
	  topSj:{
		  bankId:'',
		  bankName:'',
		  candidateId:'',
	  }
    };
  },
  computed: {
	  displayTime() {
	        const minutes = Math.floor(this.timeLeft / 60);
	        const seconds = this.timeLeft % 60;
			this.minutes = minutes
	        return `${minutes}分${seconds}秒`; // 格式化显示剩余时间
	      },
    currentQuestion() {
		console.log(this.questionsVOS[this.currentQuestionIndex],"666")
		if(this.questionsVOS[this.currentQuestionIndex].isPublic == 0 && !this.countdownStarted){
			this.timeshow = true
			this.countdownStarted = true; // 设置为 true，表示倒计时已启动
			this.startCountdown()
		}
      return this.questionsVOS[this.currentQuestionIndex];
    }
  },
  onLoad(opt) {
	  console.log(this.currentQuestion.optionsVOS,"currentQuestion.optionsVOScurrentQuestion.optionsVOS")
	  // this.$http.get('api/examQuestionBank/getById',{
	  // 	id:145
	  // }).then(res1 => {
	  // 	uni.navigateTo({
	  // 		url:`/pages/dati/chengjidan?res=${JSON.stringify(res1.result)}`
	  // 	})
	  // })
	
	let obj = JSON.parse(uni.getStorageSync('tmData'))
	this.ksid = obj.id
	// 过滤出respondAnswers为null的数据
	let filteredRes = obj.questionsVOS.filter(item => item.respondAnswers === null);
	// 获取上次保存的进度
	let savedProgress = null
	console.log(uni.getStorageSync('quizProgress'),"uni.getStorageSync('quizProgress')")
	if(uni.getStorageSync('quizProgress')){
		savedProgress = JSON.parse(uni.getStorageSync('quizProgress'))
		if(savedProgress.minutes){
			let minu = this.datanext(savedProgress.date,this.getTime())
			if(minu > savedProgress.minutes){
				console.log('考试时间已经结束')
				clearInterval(that.countdown);
				this.showPopup1 = true
				uni.removeStorageSync('quizProgress')
			}else{
				this.totalMinutes = savedProgress.minutes - minu
			}
		}else{
			this.totalMinutes =obj.time
		}
		// 如果有保存的题目索引，恢复它
	  if (savedProgress.currentQuestionIndex) {
		  this.currentQuestionIndex = savedProgress.currentQuestionIndex;
	  }
	  if(savedProgress.list){
	  	  console.log(JSON.parse(savedProgress.list),"zqt")
	  	  this.questionsVOS = JSON.parse(savedProgress.list)
	  }
	  this.isPublic3Array = JSON.parse(uni.getStorageSync('isPublic3Array'))
	  // uni.setStorageSync('isPublic3Array', JSON.stringify(this.isPublic3Array));
	}else{
		console.log("wojinlaile ")
		this.totalMinutes = obj.time
		this.questionsVOS = obj.questionsVOS
		
		this.questionsVOS = filteredRes
		this.questionsVOS.forEach(question => {
			if(question.optionsVOS){
				question.optionsVOS = question.optionsVOS.map(option => ({
				    ...option,
				    selected: false // 添加 selected 属性，默认为 false
				})).sort((a, b) => {
				    // 使用 ASCII 码排序，以确保 A, B, C 的顺序
				    return a.number.localeCompare(b.number);
				});
			}
		    
		});
		
		
	}
	
  
      this.arr2QuestionsVOS = obj.questionsVOS
      //创建一个新数组用来打乱选项顺序（无选项题直接返回原题目）
      this.questionsVOS = this.questionsVOS.map(question => {
          if(!question.optionsVOS || question.optionsVOS.length === 0){
              return { ...question };
          }
          // 深拷贝 `optionsVOS` 并打乱顺序
          const shuffledOptions = [...question.optionsVOS].sort(() => Math.random() - 0.5);
          return { ...question, optionsVOS: shuffledOptions };
      });
      this.isPublic3Array = this.questionsVOS.filter(item => item.isPublic == 3);
      this.questionsVOS = this.questionsVOS.filter(item => item.isPublic != 3);
      this.isPublic3Array.forEach(question => {
      	if(question.optionsVOS){
      		question.optionsVOS = question.optionsVOS.map(option => ({
      		    ...option,
      		    selected: false // 添加 selected 属性，默认为 false
      		}))
      	}
      
      });
	  uni.setStorageSync('isPublic3Array',this.isPublic3Array)
	  console.log(this.isPublic3Array,"this.isPublic3Array")
	  console.log("打乱顺序后的显示数组:", this.questionsVOS);
	console.log(filteredRes,"obj")
	console.log(obj.questionsVOS,"obj")
	// 如果有保存的倒计时，恢复它
	  // if (savedProgress.timeLeft) {
	  //     this.totalMinutes = 21;
	  //     // this.startCountdown(); // 恢复倒计时
	  // } else {
	  //     this.totalMinutes = obj.time
	  // }

	this.topSj.bankId = obj.bankId
	this.topSj.bankName = obj.bankName
	this.topSj.candidateId = obj.candidateId
	// this.questionsVOS = filteredRes
	// 为每个选项添加 selected 属性，并根据 number 排序
	// console.log(this.questionsVOS,"this.questionsVOS")
	
	
  	// 隐藏原生的tabbar
  	uni.hideTabBar();
  },
  methods: {
	  // 图片预览 - 自定义预览组件，确保最高层级
	  previewImage(url) {
		  this.currentImageUrl = url;
		  this.showImagePreview = true;
		  this.imageScale = 1;
		  this.imagePosition = { x: 0, y: 0 };
		  
		  // H5平台添加滚轮缩放支持
		  // #ifdef H5
		  this.$nextTick(() => {
			  const container = document.querySelector('.image-preview-container');
			  if (container) {
				  const wheelHandler = (e) => {
					  e.preventDefault();
					  const delta = e.deltaY > 0 ? 0.9 : 1.1;
					  const newScale = Math.max(1, Math.min(5, this.imageScale * delta));
					  this.imageScale = newScale;
					  if (this.imageScale === 1) {
						  this.imagePosition = { x: 0, y: 0 };
					  }
				  };
				  container.addEventListener('wheel', wheelHandler, { passive: false });
				  // 保存处理器引用，以便后续移除
				  this._wheelHandler = wheelHandler;
			  }
		  });
		  // #endif
	  },
	  closeImagePreview() {
		  this.showImagePreview = false;
		  this.imageScale = 1;
		  this.imagePosition = { x: 0, y: 0 };
		  
		  // H5平台移除滚轮事件监听
		  // #ifdef H5
		  if (this._wheelHandler) {
			  const container = document.querySelector('.image-preview-container');
			  if (container) {
				  container.removeEventListener('wheel', this._wheelHandler);
			  }
			  this._wheelHandler = null;
		  }
		  // #endif
	  },
	  // 图片触摸事件处理
	  onImageTouchStart(e) {
		  if (e.touches.length === 2) {
			  // 双指缩放
			  const dx = e.touches[0].clientX - e.touches[1].clientX;
			  const dy = e.touches[0].clientY - e.touches[1].clientY;
			  this.lastTouchDistance = Math.sqrt(dx * dx + dy * dy);
			  this.touchStartScale = this.imageScale;
		  } else if (e.touches.length === 1) {
			  // 单指移动
			  this.touchStart = { x: e.touches[0].clientX, y: e.touches[0].clientY };
		  }
	  },
	  onImageTouchMove(e) {
		  if (e.touches.length === 2) {
			  // 双指缩放
			  const dx = e.touches[0].clientX - e.touches[1].clientX;
			  const dy = e.touches[0].clientY - e.touches[1].clientY;
			  const distance = Math.sqrt(dx * dx + dy * dy);
			  const scale = (distance / this.lastTouchDistance) * this.touchStartScale;
			  this.imageScale = Math.max(1, Math.min(5, scale)); // 限制在1-5倍之间
		  } else if (e.touches.length === 1 && this.imageScale > 1) {
			  // 单指移动（仅在放大时）
			  const deltaX = e.touches[0].clientX - this.touchStart.x;
			  const deltaY = e.touches[0].clientY - this.touchStart.y;
			  this.imagePosition.x = deltaX;
			  this.imagePosition.y = deltaY;
		  }
	  },
	  onImageTouchEnd(e) {
		  // 重置触摸状态
		  if (this.imageScale <= 1) {
			  this.imageScale = 1;
			  this.imagePosition = { x: 0, y: 0 };
		  }
	  },
	  // 双击缩放（H5平台）
	  onImageDoubleClick() {
		  if (this.imageScale === 1) {
			  this.imageScale = 2;
		  } else {
			  this.imageScale = 1;
			  this.imagePosition = { x: 0, y: 0 };
		  }
	  },
	  qued(){
		  uni.reLaunch({
		      url: '/pages/dati/index'
		  });
	  },
	  //两个时间相减得到的分钟
	  datanext(cachedTimeString, currentTimeString) {
	      console.log(cachedTimeString, "cachedTimeString");
	      console.log(currentTimeString, "currentTimeString");
	   
	      // 直接将时间字符串转换为 Date 对象，不需要替换 T00:00:00
	      // 但为了更兼容，我们可以将 / 替换为 - 并确保格式是 YYYY-MM-DD HH:mm（这是 ISO 8601 的一个变种）
	      const cachedTime = new Date(cachedTimeString.replace(/\//g, '-') + ' ' + '00:00:00'.slice(cachedTimeString.indexOf(' ') + 3).replace(/:/g, ''));
	      // 上面的替换其实是不必要的，因为我们只是想要保留原始时间，所以应该这样做：
	      // const cachedTime = new Date(cachedTimeString.replace(/\//g, '-') + (cachedTimeString.includes(' ') ? 'T' + cachedTimeString.split(' ')[1] : 'T00:00:00'));
	      // 但更简单且正确的方法是直接这样：
	      const cachedTimeSimple = new Date(cachedTimeString.replace(/\//g, '-') + (cachedTimeString.includes(' ') ? 'T' + cachedTimeString.split(' ')[1] : ''));
	      // 对于 currentTime 也做同样的处理，但既然我们知道它们格式相同，只需确保不改变时间部分即可
	      const currentTimeSimple = new Date(currentTimeString.replace(/\//g, '-') + (currentTimeString.includes(' ') ? 'T' + currentTimeString.split(' ')[1] : ''));
	   
	      // 然而，上面的处理仍然过于复杂。既然我们知道输入格式是 "YYYY/MM/DD HH:mm"，
	      // 我们可以直接按部分解析它，或者更简单地，只替换日期部分的斜杠：
	      const cachedTimeCorrect = new Date(`${cachedTimeString.slice(0, 10).replace(/\//g, '-')}T${cachedTimeString.slice(11)}`);
	      const currentTimeCorrect = new Date(`${currentTimeString.slice(0, 10).replace(/\//g, '-')}T${currentTimeString.slice(11)}`);
	   
	      console.log(cachedTimeCorrect, "cachedTimeCorrect");
	      console.log(currentTimeCorrect, "currentTimeCorrect");
	   
	      // 计算毫秒数差值
	      const timeDifferenceInMilliseconds = currentTimeCorrect - cachedTimeCorrect;
	      console.log(timeDifferenceInMilliseconds, "timeDifferenceInMilliseconds");
	   
	      // 将毫秒数转换为分钟
	      const timeDifferenceInMinutes = timeDifferenceInMilliseconds / (1000 * 60);
	   
	      return timeDifferenceInMinutes;
	  },
	  getTime(){
		  // 创建一个新的Date对象，表示当前时间
		  const now = new Date();
		   
		  // 获取年份、月份、日期、小时和分钟
		  const year = now.getFullYear();
		  const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并使用padStart确保有两位数字
		  const day = String(now.getDate()).padStart(2, '0'); // 使用padStart确保有两位数字
		  const hours = String(now.getHours()).padStart(2, '0'); // 使用padStart确保有两位数字
		  const minutes = String(now.getMinutes()).padStart(2, '0'); // 使用padStart确保有两位数字
		   
		  // 格式化日期时间为"YYYY/MM/DD HH:mm"
		  const formattedDateTime = `${year}/${month}/${day} ${hours}:${minutes}`;
		  return formattedDateTime;
	  },
	  startCountdown() {
		  // if(this.totalMinutes == 0 ){
			 //  return
		  // }
	        clearInterval(this.countdown); // 清除之前的计时器
	        this.timeLeft = this.totalMinutes * 60; // 将分钟转换为秒
	        this.updateCountdown(); // 开始更新倒计时
	      },
	      updateCountdown() {
	        this.countdown = setInterval(() => {
				console.log(999)
	          this.timeLeft--;
				let obj = {
						  minutes:this.minutes,
						  date:this.getTime()
				}
				let obj1 = {
						  minutes:"",
						  date:''
				}
				if(this.currentQuestion.isPublic == 0){
						  this.saveProgress(obj);
				}else{
						  this.saveProgress(obj1);
				}
	          if (this.timeLeft < 0) {
	            clearInterval(this.countdown);
	            this.onCountdownEnd(); // 倒计时结束时调用方法
	          }
	        }, 1000); // 每秒更新一次
	      },
	      onCountdownEnd() {
	        uni.showToast({
	          title: '时间到！',
	          icon: 'none',
	        });
	        // 在这里可以调用你需要执行的方法
	      },
	  //提交答卷
	  tijiaodajuan(){
		  let that = this
		  store.commit("setLoadingShow", true);
		  this.unansweredQuestions = [];  
			this.questionsVOS.forEach((question, index) => {  
			  // 无选项题：用文本输入值参与未填校验
			  const hasOptions = question.optionsVOS && question.optionsVOS.length > 0
			  const finalAnswer = hasOptions ? (question.respondAnswers || '') : ((question.fillAnswer || '').trim())
			  if (!finalAnswer || finalAnswer.trim() === '') {  
				// 如果respondAnswers为空或只包含空白字符，则认为该题未填写  
				this.unansweredQuestions.push(` 第${index + 1}题`);  
			  }  
			});  
		if (this.unansweredQuestions.length > 0) {  
			this.unansweredQuestionsStr = '未填写题目:'+this.unansweredQuestions.join(', ')
			store.commit("setLoadingShow", false);
		}else{
			console.log(this.questionsVOS,"questionsVOS")
			// 遍历每个问题  
			this.questionsVOS.forEach(question => {  
			    // 无选项题：在提交前封装一个默认A选项，isPublic=1，content为输入值
			    if(!question.optionsVOS || question.optionsVOS.length === 0){
			        const inputVal = (question.fillAnswer || '').trim()
			        question.respondAnswers = inputVal
			        question.optionsVOS = [
			        	{
			        		id: question.id ? Number(`${question.id}01`) : 1,
			        		questionId: question.id,
			        		content: inputVal,
			        		number: 'A',
			        		isPublic: 1
			        	}
			        ]
			    }
			    // 遍历每个问题的选项  
			    question.optionsVOS.forEach(option => {  
			        // 使用delete关键字删除selected字段  
			        delete option.selected;  
			    });  
			});
			console.log(this.questionsVOS,"questionsVOS")
			this.arr2QuestionsVOS = this.arr2QuestionsVOS.map(item => {
			    // 在 arr1 中查找匹配的项
			    const match = this.questionsVOS.find(item1 => item1.id === item.id);
			    // 如果找到了匹配项，则替换；否则保留原项
			    return match ? { ...match } : item;
			});
			this.arr2QuestionsVOS = this.arr2QuestionsVOS.map(item => {
			    // 在 arr1 中查找匹配的项
			    const match = this.subarr2.find(item1 => item1.id === item.id);
			    // 如果找到了匹配项，则替换；否则保留原项
			    return match ? { ...match } : item;
			});
			let objopt = {
				bankId:this.topSj.bankId,
				bankName:this.topSj.bankName,
				candidateId:this.topSj.candidateId,
				questionsVOS:this.arr2QuestionsVOS
				// questionsVOS:JSON.stringify(this.questionsVOS)
			}
			that.$http.post('api/examQuestionBank/submit',objopt).then(res => {
					if (res.code == 200) {
						that.showPopup  = false
						uni.showToast({
							title: "提交成功"
						});
						that.getKS(that.ksid)
						clearInterval(that.countdown);
						uni.removeStorageSync('quizProgress')
						uni.removeStorageSync('isPublic3Array')
						setTimeout(function(){
							// uni.reLaunch({
							//     url: '/pages/dati/index'
							// });
							
							that.$http.get('api/examQuestionBank/getById',{
								id:that.topSj.candidateId
							}).then(res1 => {
								uni.navigateTo({
									url:`/pages/dati/chengjidan?res=${JSON.stringify(res1.result)}`
								})
							})
							// that.$http.post('api/examQuestionBank/getById',{
							// 	id:145
							// }).then(res1 => {
							// 	uni.navigateTo({
							// 		url:`/pages/dati/chengjidan?res=${res1.result}`
							// 	})
							// })
							
						},1500)
					} else {
						that.showPopup  = false
						uni.showToast({
							title:res.message
						});
					}
				}, err => {
					that.showPopup  = false
					uni.showToast({
						title:'提交失败,错误原因:'+err.errMsg,
						icon: "none"
					});
					console.log(err,"324242")
				});
			this.unansweredQuestionsStr = ''
		}
		  //请求接口
	  },
	  getKS(ids){
		  let obj = {
		  		id:ids,
		  		type:2
		  	}
		  	uni.request({
		  	  url: 'http://124.222.44.60:9090/jeecg-boot/h5/api/examQuestionBank/submitRecordsLog',
		  	  method: 'GET',
		  	  // header: {
		  	  //   'Content-Type': 'application/x-www-form-urlencoded'
		  	  // },
		  	  data:obj,
		  	  success: (res) => {
		  		  if(res.data.code==200){
		  			 }
		  	  },
		  	  fail: (err) => {
		  		  uni.showToast({
		  		  	title: err,
		  		  	icon: "none"
		  		  });
		  		  store.commit("setLoadingShow", false);
		  	    console.error('请求失败:', err);
		  	  }
		  	});
		 
	  },
	  backClick(){
		  
	  },
	  submits(){
		  // 无选项题：校验文本输入
		  if((!this.currentQuestion.optionsVOS || this.currentQuestion.optionsVOS.length === 0)){
		  	const inputVal = (this.currentQuestion.fillAnswer || '').trim()
		  	if(!inputVal){
		  		uni.showToast({
		  			title:'请输入答案',
		  			icon: "none"
		  		});
		  		return
		  	}
		  	this.currentQuestion.respondAnswers = inputVal
		  }
		  if(!this.currentQuestion.respondAnswers){
		  	uni.showToast({
		  		title:'选项不能为空',
		  		icon: "none"
		  	});
		  	return
		  }
		  this.showPopup = true
	  },
    selectOption(index) {
		
		if(this.ShowPub3res.length >0){
			const question = this.ShowPub3res[0];
			  if(question.respondAnswers == null){
				  question.respondAnswers = ''
			  }
			if (question.isMultipleChoice) {
			  question.optionsVOS[index].selected = !question.optionsVOS[index].selected;
				if(!question.optionsVOS[index].selected){  //如果是多选取消选择的时候
					question.respondAnswers = question.respondAnswers.replace(new RegExp(question.optionsVOS[index].number, 'g'), '');
				}else{ //如果是多选选择的时候
					question.respondAnswers+=question.optionsVOS[index].number
				}
				this.subarr2.push(question)
				console.log(question,"我是关联题目")
			} else {
			  question.optionsVOS.forEach((option, i) => option.selected = i === index);
				question.respondAnswers = question.optionsVOS[index].number
				this.subarr2.push(question)
				console.log(question,"我是关联题目")
			}
			// console.log(this.ShowPub3res)
			// this.ShowPub3res[0].optionsVOS.forEach((option, i) => option.selected = i === index);
			// question
			// this.questionsVOS[this.currentQuestionIndex];
		}else{
			    const question = this.currentQuestion;
				  if(question.respondAnswers == null){
					  question.respondAnswers = ''
				  }
			    if (question.isMultipleChoice) {
			      question.optionsVOS[index].selected = !question.optionsVOS[index].selected;
					if(!question.optionsVOS[index].selected){  //如果是多选取消选择的时候
						question.respondAnswers = question.respondAnswers.replace(new RegExp(question.optionsVOS[index].number, 'g'), '');
					}else{ //如果是多选选择的时候
						question.respondAnswers+=question.optionsVOS[index].number
					}
					console.log(question.respondAnswers,"question.respondAnswers")
			    } else {
			      question.optionsVOS.forEach((option, i) => option.selected = i === index);
					question.respondAnswers = question.optionsVOS[index].number
					this.indexvo = question.optionsVOS[index]
					console.log(question.optionsVOS[index],"question.respondAnswers")
			    }
		}
  
    },
    isSelected(index) {
		// console.log(this.currentQuestion)
		// console.log("isSelected",this.currentQuestion.optionsVOS[index].selected)
		if(this.ShowPub3res.length >0){
			// this.questionsVOS[this.currentQuestionIndex];
			console.log(this.ShowPub3res)
			console.log(index)
			return this.ShowPub3res[0].optionsVOS[index].selected;
		}else{
			console.log(this.currentQuestion.optionsVOS[index].selected,"this.currentQuestion.optionsVOS[index].selected")
			return this.currentQuestion.optionsVOS[index].selected;
		}
      
    },
    nextQuestion() {
		if(this.ShowPub3res.length >0){
			if(!this.ShowPub3res[0].respondAnswers){
				uni.showToast({
					title:'选项不能为空',
					icon: "none"
				});
				return
			}else{
				this.ShowPub3res = []
				this.indexvo = null
			}
		}
		if(this.indexvo){
			if(this.indexvo.other){
				console.log(this.isPublic3Array)
				this.ShowPub3res = this.isPublic3Array.filter(item=>item.id == this.indexvo.other )
				
				// console.log(res,"this.indexvo.other")
				return
			}
		}
		
        console.log(this.currentQuestion,"yes")
        // 无选项题校验：必须先输入
        if(!this.currentQuestion.optionsVOS || this.currentQuestion.optionsVOS.length === 0){
            const inputVal = (this.currentQuestion.fillAnswer || '').trim()
            if(!inputVal){
                uni.showToast({
                    title:'请输入答案',
                    icon: "none"
                });
                return
            }
            this.currentQuestion.respondAnswers = inputVal
        }
        if(!this.currentQuestion.respondAnswers){
            uni.showToast({
                title:'选项不能为空',
                icon: "none"
            });
            return
        }
      if (this.currentQuestionIndex < this.questionsVOS.length - 1 && !this.transitioning) {
        this.currentQuestionIndex++;
		this.transitioning = true;  // 开始动画时禁止多次点击
        this.animateTransition('next');
		this.transitioning = false;  // 开始动画时禁止多次点击
      }
	  let obj = {
		  minutes:this.minutes,
		  date:this.getTime()
	  }
	  let obj1 = {
	  		  minutes:"",
	  		  date:''
	  }
	  if(this.currentQuestion.isPublic == 0){
		  this.saveProgress(obj);
	  }else{
		  this.saveProgress(obj1);
	  }
	  
    },
    prevQuestion() {
		if(this.ShowPub3res.length >0){
				this.ShowPub3res = []
				this.indexvo = null
		}
      if (this.currentQuestionIndex > 0 && !this.transitioning) {
        this.currentQuestionIndex--;
		this.transitioning = true;  // 开始动画时禁止多次点击
        this.animateTransition('prev');
		this.transitioning = false;  // 开始动画时禁止多次点击
      }
	  let obj = {
	  		  minutes:this.minutes,
	  		  date:this.getTime()
	  }
	  let obj1 = {
	  		  minutes:"",
	  		  date:''
	  }
	  if(this.currentQuestion.isPublic == 0){
	  		  this.saveProgress(obj);
	  }else{
	  		  this.saveProgress(obj1);
	  }
	  
    },
	saveProgress(data) {
		// console.log(this.questionsVOS,"this.questionsVOSthis.questionsVOSthis.questionsVOSthis.questionsVOS")
		const progress = {
			currentQuestionIndex: this.currentQuestionIndex,
			list:JSON.stringify(this.questionsVOS),
			timeLeft: this.timeLeft,
			minutes:data.minutes,
			date:data.date
		};
		uni.setStorageSync('quizProgress', JSON.stringify(progress));
	},
    animateTransition() {
	      
	}  
  }
};
</script>




<style lang="scss">
	.mask {  
	  position: fixed;  
	  top: 0;  
	  left: 0;  
	  width: 100%;  
	  height: 100%;  
	  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */  
	  z-index: 1000; /* 确保遮罩层在弹出层之下 */  
	  display: flex;  
	  justify-content: center;  
	  align-items: center;  
	}  
	// position: absolute;
	// background-color: #000;
	// border-radius: 30px;
	// padding: 20px;
	// width: 100%;
	// box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
	// margin-bottom: 20px;
	// overflow: hidden;
	.tjda{
		border-radius: 10px;
		box-shadow: 1px 1px 4px 1px rgba(0, 0, 0, 0.1);
		background-color: #ffffff;
		height: 550rpx;
		width: 80%;
		position: absolute;
		top: 0;
		margin-top: 50%;
		margin-left: 4%;
		z-index: 9999 ;
	}
	.tjda1{
		border-radius: 10px;
		box-shadow: 1px 1px 4px 1px rgba(0, 0, 0, 0.1);
		background-color: #ffffff;
		height:300rpx;
		width: 80%;
		position: absolute;
		top: 0;
		margin-top: 70%;
		margin-left: 4%;
		z-index: 9999 ;
	}
	/* 动画效果 */
	.fade-enter-active, .fade-leave-active {
	  transition: opacity 0.5s;
	}
	
	.fade-enter, .fade-leave-to {
	  opacity: 0;
	}

	/* 问题切换动画 */
	.question-wrapper{
		animation: question-wrapper .6s both;
	}

	@keyframes question-wrapper {
		0%{
			transform: scale(.8);
			opacity: 0;
		}
		99%{
			transform: scale(1);
			opacity: 1;
		}
		100%{
			transform: scale(1);
			opacity: 1;
		}
	}

	.aniNext{
		animation: aniNext .6s both;
	}

	@keyframes aniNext {
		0%{
			transform: translate(0,0) scale(1);
			opacity: 1;
		}
		95%{
			transform: translate(-120%,50%) scale(.8) rotate(-30deg);
			opacity: 0;
		}
		100%{
			transform: translate(-120%,50%) scale(.8) rotate(-30deg);
			opacity: 0;
		}
	}
/* 页面整体样式 */
.quiz-page {
	background-image: url('../../static/dati/tm_01.png');
	background-position: center; /* 图片居中 */  
	  background-repeat: no-repeat; /* 不重复 */  
	  background-size: cover; /* 覆盖整个元素，保持宽高比 */  
	  background-attachment: fixed; /* 可选，使背景图在滚动时不滚动 */
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 头部区域样式 */
.header-section {
  margin-top: 50px;
	font-size: 27px;
//   color: white;
color: rgb(0, 0, 0);
font-weight: 700;
  text-align: center;
}

.subtitle-text {
  font-size: 20px;
  
  opacity: 0.9;
  text-align: center;
}

.progress-text {
  font-size: 20px;
  opacity: 0.8;
  text-align: center;
}

/* 问题外层大白色圆角框 - 拉长版本 */
.question-wrapper {
  position: relative;
  z-index: 9998;
  background-color: #ffffff;
  border-radius: 30px;
  padding: 20px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  flex: 1;
  margin: 20px 0;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  min-height: 50vh;
  overflow: auto
}

/* 问题内部容器 */
.question-container {
  border-radius: 15px;
//   padding: 15px;
//   margin-bottom: 20px;
}

.question {
  font-size: 18px;
  color: #333;
  text-align: left;
  font-weight: 500;
}

/* 问题图片样式 */
.question-image {
  width: 100%;
  margin: 15px 0;
  display: block;
  cursor: pointer;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.question-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.question-flex {
  display: flex;
  flex-direction: column;
}

/* 图片预览遮罩层 - 最高层级 */
.image-preview-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 99999; /* 确保在最顶层 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-preview-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  transition: transform 0.1s ease-out;
  cursor: move;
}

.image-preview-close {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #333;
  cursor: pointer;
  z-index: 100000;
  font-weight: bold;
}

.image-preview-close:hover {
  background-color: rgba(255, 255, 255, 1);
}

/* 选项样式 */
.option {
  margin-bottom: 15px;
}

.option-text {
  padding: 15px 20px;
  background-color: #f5f5f5;
  border-radius: 10px;
  font-size: 16px;
  transition: all 0.3s ease;
}

.option-text.selected {
  background: linear-gradient(160deg, #59cc8f, #148677);
  color: white;
}

/* 底部导航按钮样式 */
.bottom-navigation {
  display: flex;
  justify-content: space-between;
  padding: 0px 0;
  margin-top: auto;
}

.nav-button {
  flex: 0 0 45%;
  padding: 15px 0;
  background: linear-gradient(160deg, #59cc8f, #148677);
  border-radius: 50px;
  color: white;
  font-size: 20px;
  border: none;
  height: 100rpx;
  line-height: 50rpx;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
}

.nav-button:disabled {
  opacity: 0.6;
}

.nav-button1 {
  flex: 1;
  margin: 0 10px;
  background: linear-gradient(160deg, #59cc8f, #148677);
  border-radius: 25px;
  color: white;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 16px;
  border: none;
  box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2);
}
</style>
